package com.example.myenglishbook.database;


import android.content.Context;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import java.util.List;

public class WordsRepository {
    private WordsDatabase wordsDatabase;
    private WordsDao wordsDao;

    public WordsRepository(Context context) {
        wordsDatabase= WordsDatabase.getINSTANCE(context);
        wordsDao=wordsDatabase.getWordsDao();
    }

    public LiveData<List<Words>> getData(){
        return wordsDao.queryAll();
    }

    public LiveData<List<Words>> findWordsWithPatten(String patten){
        return wordsDao.findWordsWithPatten("%"+patten.trim()+"%");
    }

    public void insert(Words... words){
        new InsertAsyncTask(wordsDao).execute(words);
    }

    public void update(Words... words){
        new UpdateAsyncTask(wordsDao).execute(words);
    }

    public void delete(Words... words){
        new DeleteAsyncTask(wordsDao).execute(words);
    }

    public void clear(){
        new ClearAsyncTask(wordsDao).execute();
    }

    static class InsertAsyncTask extends AsyncTask<Words,Void,Void>{
        private WordsDao wordsDao;

        public InsertAsyncTask(WordsDao wordsDao) {
            this.wordsDao = wordsDao;
        }

        @Override
        protected Void doInBackground(Words... words) {
            wordsDao.insert(words);
            return null;
        }
    }

    static class UpdateAsyncTask extends AsyncTask<Words,Void,Void>{
        private WordsDao wordsDao;

        public UpdateAsyncTask(WordsDao wordsDao) {
            this.wordsDao = wordsDao;
        }

        @Override
        protected Void doInBackground(Words... words) {
            wordsDao.update(words);
            return null;
        }
    }

    static class DeleteAsyncTask extends AsyncTask<Words,Void,Void>{
        private WordsDao wordsDao;

        public DeleteAsyncTask(WordsDao wordsDao) {
            this.wordsDao = wordsDao;
        }

        @Override
        protected Void doInBackground(Words... words) {
            wordsDao.delete(words);
            return null;
        }
    }


    static class ClearAsyncTask extends AsyncTask<Void,Void,Void>{
        private WordsDao wordsDao;

        public ClearAsyncTask(WordsDao wordsDao) {
            this.wordsDao = wordsDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            wordsDao.clear();
            return null;
        }
    }
}
